package com.atguigu.gulimall.authserver.controller;



import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberResponseVo;
import com.atguigu.gulimall.authserver.feign.MemberFeignService;
import com.atguigu.gulimall.authserver.feign.ThirdPartFeignService;

import com.atguigu.gulimall.authserver.vo.UserLoginVo;
import com.atguigu.gulimall.authserver.vo.UserRegisterVo;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.netflix.ribbon.proxy.annotation.Http;
import javafx.scene.chart.PieChart;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;


import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Controller
public class LoginController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ThirdPartFeignService thirdPartFeignService;
    @Autowired
    MemberFeignService memberFeignService;
    @ResponseBody
    @GetMapping(value = "/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone) {
        //1、接口防刷
        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(redisCode)) {
            //活动存入redis的时间，用当前时间减去存入redis的时间，判断用户手机号是否在60s内发送验证码
            long currentTime = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - currentTime < 60000) {
                //60s内不能再发
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(),BizCodeEnum.SMS_CODE_EXCEPTION.getMessage());
            }
        }
        //2、验证码的再次效验 redis.存key-phone,value-code
        int code = (int) ((Math.random() * 9 + 1) * 100000);
        String codeNum = String.valueOf(code);
        String redisStorage = codeNum + "_" + System.currentTimeMillis();
        //存入redis，防止同一个手机号在60秒内再次发送验证码
        stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone,
                redisStorage,10, TimeUnit.MINUTES);
        thirdPartFeignService.sendCode(phone, codeNum);
        return R.ok();
    }


    /**
     *
     * TODO: 重定向携带数据：利用session原理，将数据放在session中，只要跳转到下一个页面取出这个数据以后，session里面的数据就会删掉
     * TODO：分布下session问题
     * RedirectAttributes：一般来说 只有转发才能传递数据，而重定向不能保留数据 但是加上 RedirectAttributes 重定向也可以保留数据，不会丢失
     * 之所以重定向，是因为防止表单重复提交，因为重定向的时候，url路径会改变，而转发浏览器上边的url路径不会改变
     * 用户注册
     * BindingResult 用来获取实体类的校验结果
     * @return
     */
    @PostMapping(value = "/register")
    public String register(@Valid UserRegisterVo vos, BindingResult result,
                           RedirectAttributes attributes) {
        Map<String, String> errors = null; //存错误的结果
        //如果有错误回到注册页面
        if (result.hasErrors()) {
            //将所有的错误返回
            errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            attributes.addFlashAttribute("errors",errors);
            //效验出错回到注册页面
            return "redirect:http://127.0.0.1:20000/register.html";
        }
        //1、效验验证码
        String code = vos.getCode();
        //获取存入Redis里的验证码
        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vos.getPhone());
        if (!StringUtils.isEmpty(redisCode)) {
            //截取字符串
            if (code.equals(redisCode.split("_")[0])) {
                //删除验证码;令牌机制
//                stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX+vos.getPhone());
                //验证码通过，真正注册，调用远程服务进行注册
                R register = memberFeignService.register(vos);
                if (register.getCode() == 0) {
                    //成功
                    return "redirect:http://127.0.0.1:20000/login.html";
                } else {
                    //失败
                    errors = new HashMap<>();
                    errors.put("msg", register.getData("msg",new TypeReference<String>(){}));
                    attributes.addFlashAttribute("errors",errors);
                    return "redirect:http://127.0.0.1:20000/register.html";
                }
            } else {
                //效验出错回到注册页面
                errors = new HashMap<>();
                errors.put("code","验证码错误");
                attributes.addFlashAttribute("errors",errors);
                return "redirect:http://127.0.0.1:20000/register.html";
            }
        } else {
            //效验出错回到注册页面
             errors = new HashMap<>();
            errors.put("code","验证码错误");
            attributes.addFlashAttribute("errors",errors);
            return "reg";
        }
    }

    @PostMapping(value = "/login")
    public String login(UserLoginVo userLoginVo
            ,RedirectAttributes attributes
            , HttpServletResponse response
            , @CookieValue(value = "sso_token", required = false) String sso_token) {
        if( sso_token != null && stringRedisTemplate.opsForValue().get("login:users:" + sso_token) != null){
                if(!StringUtils.isEmpty(userLoginVo.getUrl())){
                    return "redirect:"+ userLoginVo.getUrl() + "?token=" + sso_token;
                }else {
                    return "redirect:http://localhost:10000/index.html?token=" + sso_token;
                }
        }
        //远程登录
        R login = memberFeignService.login(userLoginVo);
        if (login.getCode() == 0) { //登录成功
            MemberResponseVo data = login.getData("data", new TypeReference<MemberResponseVo>() {});
            //生成的随机token
            String token = System.currentTimeMillis() +  UUID.randomUUID().toString().replaceAll("-","");
            stringRedisTemplate.opsForValue().set("login:users:" + token,JSON.toJSONString(data));
            Cookie cookie = new Cookie("sso_token", token);
            cookie.setMaxAge(100*24*60*60);
            response.addCookie(cookie);//将cookie返回传给浏览器保存
            if(userLoginVo.getUrl() != null){
                return "redirect:"+ userLoginVo.getUrl() + "?token=" + sso_token;
            }else {
                return "redirect:http://localhost:10000/index.html?token=" + sso_token;
            }
        } else {
            Map<String,String> errors = new HashMap<>();
            errors.put("msg",login.getData("msg",new TypeReference<String>(){}));
            attributes.addFlashAttribute("errors",errors);
            return "redirect:http://localhost:20000/login.html";
        }
    }

}
